package com.cliang.controller;

import com.alibaba.fastjson.JSON;
import com.cliang.common.BlogQueryVo;
import com.cliang.common.LoginReqObj;
import com.cliang.common.RespMsg;
import com.cliang.entity.Blog;
import com.cliang.entity.BlogUser;
import com.cliang.service.dao.BlogDao;
import com.cliang.service.dao.BlogUserDao;
import com.cliang.tools.Tools;
import com.cliang.tools.encription.Encription;
import com.cliang.tools.page.PagePartition;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

@Controller
@RequestMapping(value = "/public/")
public class PublicController {
    @Resource
    private BlogUserDao blogUserDao;

    @Resource
    private BlogDao blogDao;

    private ArrayList<BlogUser> loginedUsers=null;

    @RequestMapping(value = "userLogin",method = RequestMethod.POST)
    @ResponseBody
    public Object login(LoginReqObj loginReqObj, HttpSession session, HttpServletRequest request, HttpServletResponse resp) throws IOException {
        RespMsg respMsg=new RespMsg();
        String veryCode= (String) session.getAttribute("verifyCode");
        BlogUser sessionUser= (BlogUser) session.getAttribute("loginUser");
        if(loginReqObj.getCode()==null || "".equals(loginReqObj.getCode()) || !loginReqObj.getCode().toLowerCase().equals(veryCode.toLowerCase())){
            respMsg.setMessage("验证码错误");
            respMsg.setCode("00111");
//            return JSON.toJSONString(respMsg);
            return respMsg;
        }

        loginReqObj.setPassword(Encription.encodeByMD5(loginReqObj.getPassword()));     //MD5加密
        BlogUser blogUser=blogUserDao.login(loginReqObj.getUsername(),loginReqObj.getPassword());
        if(blogUser==null || blogUser.equals("")){
            respMsg.setCode("00001");
            respMsg.setMessage("用户名或密码错误！");

        }else{
            respMsg.setMessage("登录成功！");
            respMsg.setCode("11111");
            session.setAttribute("loginUser",blogUser);
            Cookie userNameCookie=new Cookie("userName",blogUser.getBuNickname());
            userNameCookie.setComment("www.jinshangjing.xin");  //Cookie描述
            userNameCookie.setMaxAge(20*60);       //Cookie有效时间,单位为秒
            userNameCookie.setPath("/blog/private/");             //Cookie有效路径

            //通过response对象将Cookie写入浏览器，当然需要解决中文乱码问题，否则会抛出异常
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=UTF-8");
            resp.addCookie(userNameCookie);

//            loginedUsers.add(blogUser);
        }
//        return JSON.toJSONString(respMsg);
        return respMsg;
    }


    @RequestMapping(value = "logout")
    @ResponseBody
    public void logout(HttpServletRequest request, HttpServletResponse resp) throws IOException, ServletException {
        HttpSession session=request.getSession();
        session.invalidate();
        Cookie[] cookies=request.getCookies();
        if(cookies!=null && cookies.length>0){
            for(Cookie cookie:cookies){
                if(cookie.getName().equals("userName")){
                    cookie.setMaxAge(0);        //设置Cookie失效
                    resp.addCookie(cookie);     //重新保存Cookie
                }
            }
        }
//        PrintWriter printWriter=resp.getWriter();
//        request.getRequestDispatcher("/blog/login/login.html").forward(request,resp);
//        printWriter.close();
    }

    @RequestMapping(value = "getBlogLists",method = RequestMethod.POST)
    @ResponseBody
    public Object getBlogLists(HttpServletRequest request,HttpServletResponse resp) throws Exception {
        request.getParameter("");
        int currentPage=request.getParameter("currentPage")!=null ? Integer.valueOf(request.getParameter("currentPage")) : 1;
        int pageSize=request.getParameter("pageSize")!=null ? Integer.valueOf(request.getParameter("pageSize")) : 20;

        BlogQueryVo blogQueryVo=new BlogQueryVo();
        if(request.getParameter("btid")!=null ){
            blogQueryVo.setbId(Integer.valueOf(request.getParameter("btid")));
        }

        if(request.getParameter("bAuthor")!=null || !("").equals(request.getParameter("bAuthor"))){
            blogQueryVo.setbAuthor(request.getParameter("aAuthor"));
        }

        PagePartition<Blog> pageBlog=blogDao.getBlogList(blogQueryVo,currentPage,pageSize);

        for(int i=0;i<pageBlog.getList().size();i++){
            pageBlog.getList().get(i).setbContent(Tools.getTextFromHtml(pageBlog.getList().get(i).getbContent(),50));
        }

//        return JSON.toJSONString(pageBlog);
        return pageBlog;
    }


}
